<template>
  <ele-page flex-table>
    <ComHeader :title="isUpdate ? `编辑盘点单[${info.order_sn}]` : '新增盘点单'" @back="goBack()" />
    <ele-bottom-bar v-if="!info.id || info.is_ed === 1" :teleported="true">
      <template #extra>
        <el-button type="primary" :loading="loading" @click="save">保存</el-button>
      </template>
    </ele-bottom-bar>
    <ele-card flex-table>
      <el-scrollbar>
        <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="form" :rules="rules" label-width="60">
          <el-row>
            <el-col :md="6" :sm="12">
              <el-form-item label="仓库" prop="warehouse_id">
                <el-select v-model="form.warehouse_id" placeholder="请选择仓库" clearable @change="warehouseChange">
                  <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="12" :sm="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="备注信息" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品信息" label-position="top" label-width="200px" prop="product">
            <template #label>
              <span class="flex-inline items-center">
                <div class="">商品信息</div>
                <div class="ml-12px">
                  <el-button
                    type="primary"
                    icon="IconElPlus"
                    :disabled="!form.warehouse_id"
                    plain
                    @click="showProduct = true"
                  >
                    新增商品
                  </el-button>
                </div>
              </span>
            </template>
            <el-table
              ref="tableRef"
              :data="form.product"
              border
              style="width: 100%"
              class="form-table"
            >
              <el-table-column type="index" label="序" width="60" align="center" />
              <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
              <el-table-column prop="product_code" label="商品编码" align="center" />
              <el-table-column prop="unit" label="主单位" align="center" width="120" />
              <!-- <el-table-column
                  prop="purchase_num"
                  label="商品数量"
                  align="center"
                  :width="Math.max(...form.product.map(v => v.multi_unit?.length), 1) * 110 + 60"
                >
                  <template #default="{ row, $index }">
                    <div class="flex-a">
                      <el-space>
                        <el-form-item
                          v-for="(item, i) in row.multi_unit"
                          :key="i"
                          :label-width="0"
                          :prop="`product[${$index}].multi_unit[${i}].num`"
                          :required="row.multi_unit.every(v => !Number(v.num))"
                        >
                          <el-input
                            v-model="item.num"
                            size="small"
                            class="w-100px!"
                            placeholder="数量"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                            @input="value => deHandleInput(value, $index, 'purchase_num')"
                          >
                            <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                          </el-input>
                        </el-form-item>
                      </el-space>
                      <div v-if="row.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
                        = {{ totalUnit(row.multi_unit) }}{{ row.unit }}
                      </div>
                    </div>
                  </template>
                </el-table-column> -->
              <el-table-column label="操作" width="80" align="center">
                <template #default="{ $index }">
                  <el-link type="danger" underline="never" @click="removeProduct($index)">
                    <span
                      class="text-12px"
                    >删除</span>
                  </el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <SelectProduct
        v-model="showProduct"
        :editPrice="false"
        :editNum="false"
        queryLoc
        :selecteds="form.product"
        :where="{ warehouse_id: form.warehouse_id, is_location: 1 }"
        @done="selectProduct"
      />
    </ele-card>
  </ele-page>
</template>

<script setup>
import { ListToWarehouse } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'

defineOptions({ name: 'PurchaseEdit' })
const route = useRoute()
const router = useRouter()

const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()

const formRef = ref(null)
const tableRef = ref(null)

const orderId = ref(0)

/** 是否是修改 */
const isUpdate = computed(() => orderId.value > 0)

const loading = ref(false)

const [warehouseList] = utils.useGetList(ListToWarehouse)

const showProduct = ref(false)
const info = ref({})

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  remark: '',
  warehouse_id: undefined,
  product: [],
})

/** 表单验证规则 */
const rules = reactive({
  warehouse_id: [
    {
      required: true,
      message: '请选择仓库',
      trigger: 'change',
    },
  ],
  product: [
    {
      required: false,
      message: '请选择商品',
      type: 'array',
      trigger: 'change',
      min: 0,
    },
  ],
})

function goBack(path) {
  if (!path)
    path = '/stock/inventory'
  removePageTab({ key: routeTabKey })
  router.push(path)
}

onMounted(() => {
  orderId.value = Number(route.params?.id)

  if (orderId.value) {
    getInfo()
  }
  else {
    setPageTabTitle('新增盘点单')
  }
})

function getInfo() {
  utils.get('/stockInventory/info', { id: orderId.value }).then((res) => {
    info.value = res.data
    setPageTabTitle(`编辑盘点单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
    assignFields({
      ...form,
      ...res.data,
      enclosure: utils.encodeFiles(res.data.enclosure),
    })
  })
}

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    utils.post('/stockInventory/edit', {
      id: orderId.value || undefined,
      warehouse_id: form.warehouse_id,
      remark: form.remark,
      product: form.product.map(v => ({ product_id: v.product_id })),
    })
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          if (typeof res.data?.id === 'number' && res.data.id > 0) {
            goBack(`/stock/inventory/info/${res.data.id}`)
          }
          else {
            goBack()
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function warehouseChange() {
  form.product = []
}

function selectProduct(data) {
  if (data.length) {
    data.forEach((v) => {
      v.multi_unit = utils.totalUnit(v.multi_unit) > 0 ? v.multi_unit : v.unit_list.map(d => ({ ...d, num: '' }))
    })
    form.product.push(...data)
  }
  setTimeout(() => {
    tableRef.value.doLayout()
  }, 200)
}

function removeProduct(index) {
  form.product.splice(index, 1)
}
</script>

<style lang="scss" scoped></style>
